import { useEffect, useRef } from "react";

interface LazyImageProps {
  src: string;
  className: string;
}

const LazyImage: React.FC<LazyImageProps> = ({ src, className }) => {
  const imgRef = useRef<HTMLImageElement>(null);
  useEffect(() => {
    const imgElement = imgRef.current;
    if (!imgElement) return;
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            const img = entry.target as HTMLImageElement;
            img.src = src;
            observer.unobserve(img);
          }
        });
      },
      {
        rootMargin: "100px 0px",
      }
    );
    observer.observe(imgElement);
    // const handleScroll = () => {
    //   const rect = imgElement.getBoundingClientRect();
    //   const viewHeight = Math.max(
    //     document.documentElement.clientHeight,
    //     window.innerHeight
    //   );
    //   if (rect.bottom >= 0 && rect.top <= viewHeight + 100) {
    //     imgElement.src = src;
    //     window.removeEventListener("scroll", handleScroll);
    //   }
    // };
    // window.addEventListener("scroll", handleScroll);
    // handleScroll();
  }, [src]);

  return (
    <img
      ref={imgRef}
      src=""
      alt=""
      className={className}
    />
  );
};

export default LazyImage;
